package com.heima.wemedia.interceptor;

import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.thread.UserThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 霍森彪
 * @date 2022/7/15 12:29
 */
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    //进入controller之前拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中的userId
        String userId = request.getHeader("userId");
        if (StringUtils.isBlank(userId)){
            log.warn("用户id为空");
            return false;
        }
        //将userId保存到threadlocal中
        WmUser wmUser = new WmUser();
        wmUser.setId(Integer.parseInt(userId));
        UserThreadLocal.set(wmUser);

        return true;
    }

    //在执行完之后,释放ThreadLocal,以免内存溢出
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
